package com.share.shareplatform.shareuser.config;




import com.share.shareplatform.shareuser.filter.CustomAuthenticationFilter;
import com.share.shareplatform.shareuser.filter.JwtAuthenticationFilter;
import com.share.shareplatform.shareuser.interceptor.SecurityAccessDeniedHandler;
import com.share.shareplatform.shareuser.interceptor.SecurityAuthenticationEntryPoint;
import com.share.shareplatform.shareuser.interceptor.SecurityAuthenticationFailHandler;
import com.share.shareplatform.shareuser.interceptor.SecurityAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    //注入数据源
    @Autowired
    private DataSource dataSource;

    @Autowired
    private SecurityAccessDeniedHandler securityAccessDeniedHandler;

    @Autowired
    private SecurityAuthenticationEntryPoint securityAuthenticationEntryPoint;

    @Autowired
    private SecurityAuthenticationFailHandler securityAuthenticationFailHandler;

    @Autowired
    private SecurityAuthenticationSuccessHandler securityAuthenticationSuccessHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter=new CustomAuthenticationFilter();
        //自定义登录失败成功处理
        filter.setAuthenticationSuccessHandler(securityAuthenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(securityAuthenticationFailHandler);
        filter.setFilterProcessesUrl("/user/login");
        //这句很关键，重用WebSecurityConfigurerAdapter配置的AuthenticationManager，不然要自己组装AuthenticationManager
        filter.setAuthenticationManager(authenticationManagerBean());

        return filter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http
                .authorizeRequests();

        registry.and()
                //解决springsecurity跨域问题
                .cors()
                .and()
                .formLogin()
                //.loginPage("/loginPage")
                //自定义登录失败成功处理
                /*.loginProcessingUrl("/user/loginn")*/
                /*.successHandler(securityAuthenticationSuccessHandler)
                .failureHandler(securityAuthenticationFailHandler)
                .permitAll()*/
                .and()
                .logout()
                .permitAll()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(securityAuthenticationEntryPoint)
                .accessDeniedHandler(securityAccessDeniedHandler)
                .and()

                //antMatchers配置在越前面，优先级越高
                .authorizeRequests()

                //注册可以所有人访问
                .antMatchers("/user/register")
                .permitAll()
                .antMatchers(HttpMethod.POST)
                .authenticated()
                .antMatchers(HttpMethod.PUT)
                .authenticated()

                .antMatchers(HttpMethod.DELETE)
                .authenticated()

                .and()
                //关闭跨站请求防护
                .csrf().disable()
                //前后端分离采用JWT 不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //jwt过滤
                .addFilterBefore(new JwtAuthenticationFilter(authenticationManager(), 100), UsernamePasswordAuthenticationFilter.class)
                //使用json登录，重写UsernamePasswordAuthenticationFilter的方法
                .addFilterAt(customAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
    }

    //设置不进行认证的路径
    @Override
    public void configure(WebSecurity web) throws Exception {
        //web.ignoring().antMatchers(HttpMethod.GET);
        super.configure(web);
    }
}
